import {message, Table, Button} from 'antd'
import React, {useState, useEffect} from 'react'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import {connect} from 'umi'
import {getSelectProgram, SaveAndUpdateScoreWeightsInfo,saveScoreWeightsInfoAndScoreProgram} from '../service'
import CreateForm from "@/pages/ScoreOf360/ScoreConfig/components/CreateForm";
import UpdateForm from "@/pages/ScoreOf360/ScoreConfig/components/UpdateForm";

const ConfigForm = () => {

  const [tableData, setTableData] = useState([]);
  const [visible,setVisible]=useState(false);
  const [createVisible,setCreateVisible]=useState(false);
  const [current,setCurrent] = useState(null);

  useEffect(()=>{
    getSelectProgram().then(res => {
      setTableData(res.map(item => ({key: item.id, ...item})));
    });
  },[]);

  const columns = [
    {
      title: '序号',
      key: 'index',
      render: (text,record,index) => index+1
    },
    {
      title: '评分类型',
      dataIndex: 'programName',
      key: 'programName',
    },
    {
      title: '操作',
      key: 'action',
      render: (item, record) => (
        <>
          {<a onClick={() => setConfig(record)}>配置</a>}
        </>
      ),
    },
  ];

  const setConfig = (record) => {
    setCurrent(record);
    setVisible(true);
  };

  const onFinish = (values) => {
    SaveAndUpdateScoreWeightsInfo(values).then(res => {
      if (res.flag) {
        message.success('评分权重配置成功！')
      } else {
        message.error(res.error);
      }
      onCancel();
    })
  };

  const onCreateFinish = (values) => {
    saveScoreWeightsInfoAndScoreProgram(values).then(res => {
      if (res.flag) {
        message.success('创建成功！')
        getSelectProgram().then(res => {
          setTableData(res.map(item => ({key: item.id, ...item})));
        });
      } else {
        message.error(res.error);
      }
      setCreateVisible(false)
    })
  };

  const onCancel = () => {
    setCurrent(null);
    setVisible(false);
  };


  return (
    <PageHeaderWrapper extra={<Button type="primary" onClick={() => {setCreateVisible(true)}}>新建</Button>}>

      <Table
        dataSource={tableData}
        columns={columns}
      />

      <UpdateForm
        visible={visible}
        current={current}
        onSubmit={onFinish}
        onCancel={onCancel}
      />
      <CreateForm
        visible={createVisible}
        onSubmit={onCreateFinish}
        onCancel={()=>setCreateVisible(false)}
      />

    </PageHeaderWrapper>
  )
};

export default connect(({}) => ({}))(ConfigForm)
